package org.dromara.manu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.manu.domain.ManuKpiMaster;
import org.dromara.manu.mapper.ManuKpiMasterMapper;
import org.springframework.stereotype.Service;
import org.dromara.manu.domain.bo.ManuKpiRecordBo;
import org.dromara.manu.domain.vo.ManuKpiRecordVo;
import org.dromara.manu.domain.ManuKpiRecord;
import org.dromara.manu.mapper.ManuKpiRecordMapper;
import org.dromara.manu.service.IManuKpiRecordService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 记录Service业务层处理
 *
 * @author Bin Liu
 * @date 2024-08-23
 */
@RequiredArgsConstructor
@Service
public class ManuKpiRecordServiceImpl implements IManuKpiRecordService {

    private final ManuKpiRecordMapper baseMapper;
    private final ManuKpiMasterMapper masterMapper;

    /**
     * 查询记录
     *
     * @param id 主键
     * @return 记录
     */
    @Override
    public ManuKpiRecordVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 记录分页列表
     */
    @Override
    public TableDataInfo<ManuKpiRecordVo> queryPageList(ManuKpiRecordBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ManuKpiRecord> lqw = buildQueryWrapper(bo);
        Page<ManuKpiRecordVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的记录列表
     *
     * @param bo 查询条件
     * @return 记录列表
     */
    @Override
    public List<ManuKpiRecordVo> queryList(ManuKpiRecordBo bo) {
        LambdaQueryWrapper<ManuKpiRecord> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ManuKpiRecord> buildQueryWrapper(ManuKpiRecordBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ManuKpiRecord> lqw = Wrappers.lambdaQuery();
        lqw.in(bo.getMasterIds() != null, ManuKpiRecord::getMasterId, bo.getMasterIds());
        lqw.eq(bo.getYearNum() != null, ManuKpiRecord::getYearNum, bo.getYearNum());
        lqw.eq(bo.getMonthNum() != null, ManuKpiRecord::getMonthNum, bo.getMonthNum());
        lqw.eq(bo.getWeekNum() != null, ManuKpiRecord::getWeekNum, bo.getWeekNum());
        lqw.eq(bo.getByDaily() != null, ManuKpiRecord::getByDaily, bo.getByDaily());
        lqw.eq(bo.getByShift() != null, ManuKpiRecord::getByShift, bo.getByShift());
        lqw.eq(bo.getKpiResult() != null, ManuKpiRecord::getKpiResult, bo.getKpiResult());
        return lqw;
    }

    /**
     * 新增记录
     *
     * @param bo 记录
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ManuKpiRecordBo bo) {
        ManuKpiRecord add = MapstructUtils.convert(bo, ManuKpiRecord.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改记录
     *
     * @param bo 记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ManuKpiRecordBo bo) {
        ManuKpiRecord update = MapstructUtils.convert(bo, ManuKpiRecord.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ManuKpiRecord entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int setDefault(Long[] ids) {

        AtomicInteger i = new AtomicInteger();
        //get all kpiMaster
        List<ManuKpiMaster> masters = masterMapper.selectList(Wrappers.emptyWrapper());
        //get kpiRecords according to ids
        List<ManuKpiRecord> records = baseMapper.selectBatchIds(List.of(ids));
        //set records result according to masterId
        records.forEach(record -> {
            ManuKpiMaster master = masters.stream().filter(m -> m.getId().equals(record.getMasterId())).findFirst().orElse(null);
            if(master!= null && record.getKpiResult()== null){
                i.getAndIncrement();
                record.setKpiResult(master.getDefaultResult());
            }else{
                records.remove(record);
            }
        });
        baseMapper.updateBatchById(records);

        return i.get();
    }

    @Override
    public BigDecimal sumKpiResult(ManuKpiRecordBo bo) {
        LambdaQueryWrapper<ManuKpiRecord> lqw = buildQueryWrapper(bo);
        List<ManuKpiRecord> records = baseMapper.selectList(lqw);
        BigDecimal sum = BigDecimal.ZERO;
        for (ManuKpiRecord record : records) {
            sum = sum.add(record.getKpiResult());
        }
        return sum;
    }

    @Override
    public List<ManuKpiRecord> getAnnualData(Integer year, String area) {
        ArrayList<Long> masterIds = new ArrayList<>();
        QueryWrapper<ManuKpiMaster> manuKpiMasterQueryWrapper = new QueryWrapper<ManuKpiMaster>();
        manuKpiMasterQueryWrapper.eq("scope",area);
        List<ManuKpiMaster> manuKpiMasters = masterMapper.selectList(manuKpiMasterQueryWrapper);
        manuKpiMasters.forEach(master -> {
            masterIds.add(master.getId());
        });

        QueryWrapper<ManuKpiRecord> manuKpiRecordQueryWrapper = new QueryWrapper<>();
        manuKpiRecordQueryWrapper.in("master_id",masterIds).eq("year_num",year);
        return baseMapper.selectList(manuKpiRecordQueryWrapper);
    }

}
